package com.huitong.gateway.filter;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.huitong.gateway.properties.RequestLogProperties;
import com.huitong.gateway.utils.WebFluxUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 日志过滤器 打印请求信息
 *
 * @author fromdrowning
 * @date 2024/3/18 20:19
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class LogFilter implements GlobalFilter, Ordered {

    /**
     * 开始请求时间的属性名
     */
    private static final String START_TIME = "startTime";

    /**
     * Gateway配置信息
     */
    private final RequestLogProperties requestLogProperties;

    /**
     * 打印请求信息
     *
     * @param exchange 当前请求和响应的信息
     * @param chain    过滤器链
     * @return 响应式对象
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 未开启日志直接返回
        if (!requestLogProperties.isRequestLog()) {
            return chain.filter(exchange);
        }

        ServerHttpRequest request = exchange.getRequest();
        String path = WebFluxUtils.getOriginalRequestUrl(exchange);
        String url = request.getMethod()
            .name() + " " + path;

        // 打印请求参数
        if (WebFluxUtils.isJsonRequest(exchange)) {
            log.info("[日志过滤器] 开始请求 json类型 参数:{} URL:{}", WebFluxUtils.resolveBodyFromCacheRequest(exchange), url);
        } else {
            MultiValueMap<String, String> parameterMap = request.getQueryParams();
            if (MapUtil.isNotEmpty(parameterMap)) {
                log.info("[日志过滤器] 开始请求 param类型 参数:{} URL:{}", JSONUtil.toJsonStr(parameterMap), url);
            } else {
                log.info("[日志过滤器] 开始请求 无参数 URL:{}", url);
            }
        }

        exchange.getAttributes()
            .put(START_TIME, System.currentTimeMillis());

        return chain.filter(exchange)
            .then(Mono.fromRunnable(() -> {
                Long startTime = exchange.getAttribute(START_TIME);
                if (startTime != null) {
                    log.info("[日志过滤器] 结束请求 耗时:{}ms URL:{}", System.currentTimeMillis() - startTime, url);
                }
            }));
    }

    /**
     * 设置优先级
     *
     * @return 优先级
     */
    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}
